#!/bin/bash

# LinkMate 项目上传到 Gitee 脚本
# 仓库地址: git@gitee.com:two-songs/linkmate_old.git

set -e  # 遇到错误立即退出

echo "🚀 开始上传项目到 Gitee..."
echo ""

# 检查是否已初始化 git 仓库
if [ ! -d .git ]; then
    echo "📦 初始化 Git 仓库..."
    git init
    echo "✅ Git 仓库初始化完成"
    echo ""
fi

# 检查远程仓库配置
REMOTE_URL=$(git remote get-url origin 2>/dev/null || echo "")
if [ -z "$REMOTE_URL" ]; then
    echo "🔗 添加远程仓库..."
    git remote add origin git@gitee.com:two-songs/linkmate_old.git
    echo "✅ 远程仓库已添加"
elif [ "$REMOTE_URL" != "git@gitee.com:two-songs/linkmate_old.git" ]; then
    echo "🔄 更新远程仓库地址..."
    git remote set-url origin git@gitee.com:two-songs/linkmate_old.git
    echo "✅ 远程仓库地址已更新"
else
    echo "✅ 远程仓库已配置"
fi
echo ""

# 检查 SSH 连接
echo "🔐 检查 SSH 连接..."
if ssh -T git@gitee.com 2>&1 | grep -q "successfully authenticated"; then
    echo "✅ SSH 连接正常"
else
    echo "⚠️  SSH 连接测试失败，请确保："
    echo "   1. 已配置 SSH 密钥到 Gitee"
    echo "   2. SSH 密钥已添加到 ssh-agent"
    echo ""
    read -p "是否继续？(y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi
echo ""

# 添加所有文件
echo "📝 添加文件到暂存区..."
git add .
echo "✅ 文件已添加"
echo ""

# 检查是否有变更
if git diff --cached --quiet && git diff --quiet; then
    echo "ℹ️  没有需要提交的变更"
    echo ""
else
    # 显示变更统计
    echo "📊 变更统计:"
    git status --short
    echo ""
    
    # 提交变更
    read -p "请输入提交信息 (直接回车使用默认信息): " COMMIT_MSG
    if [ -z "$COMMIT_MSG" ]; then
        COMMIT_MSG="Initial commit: LinkMate project upload"
    fi
    
    echo "💾 提交变更..."
    git commit -m "$COMMIT_MSG"
    echo "✅ 提交完成"
    echo ""
fi

# 检查分支
CURRENT_BRANCH=$(git branch --show-current 2>/dev/null || echo "main")
if [ -z "$CURRENT_BRANCH" ]; then
    CURRENT_BRANCH="main"
    git branch -M main
    echo "📌 创建并切换到 main 分支"
    echo ""
fi

# 推送到远程仓库
echo "⬆️  推送到 Gitee..."
echo "   分支: $CURRENT_BRANCH"
echo "   仓库: git@gitee.com:two-songs/linkmate_old.git"
echo ""

# 首次推送需要设置上游分支
if ! git rev-parse --abbrev-ref --symbolic-full-name @{u} >/dev/null 2>&1; then
    echo "首次推送，设置上游分支..."
    git push -u origin "$CURRENT_BRANCH"
else
    git push
fi

echo ""
echo "✅ 项目上传完成！"
echo ""
echo "📋 仓库信息:"
echo "   - 地址: https://gitee.com/two-songs/linkmate_old"
echo "   - SSH:  git@gitee.com:two-songs/linkmate_old.git"
echo "   - 分支: $CURRENT_BRANCH"
echo ""

